<template>
  <!-- 协同审批 -->
  <div class="collaborativeApprovalPage">
<!--    <CommonTitle titleName="合同模板">
      <template #rightCnBox v-if="contractTemplate.length > 6">
        <div class="rightCnBox" @click="onOpenChange">
          <img
            class="rightCnBox-icon"
            v-if="!isOpen"
            src="@/assets/iconImg/packUp_icon.png"
          />
          <img
            class="rightCnBox-icon"
            v-else
            src="@/assets/iconImg/open_icon.png"
          />
          <span class="rightCnBox-title">{{
            isOpen === true ? "展开" : "收起"
          }}</span>
        </div>
      </template>
    </CommonTitle>
    <div
      class="template-list"
      :style="{
        height: isOpen === true ? '' : height + 'px',
        overflow: isOpen === true ? '' : 'hidden',
      }"
    >
      <div
        class="template-item"
        v-for="(item, index) in contractTemplate"
        @click="onTemplateClick(item)"
        :key="index"
      >
        <img class="template-icon" :src="item.icon" />
        <span class="template-title">{{ item.templateName }}</span>
      </div>
    </div>-->

    <CommonTitle titleName="创建表单" class="m-t10"></CommonTitle>
    <div class="form-list">
      <div
        class="card-box"
        v-for="(item, index) in cardList"
        @click="toCreateFormPage(item, index)"
        :key="index"
      >
        <img class="card-icon" :src="item.icon" />
        <span class="card-title">{{ item.title }}</span>
      </div>
    </div>

    <CommonTitle titleName="列表" class="m-t10"></CommonTitle>
    <div class="menu-list">
      <el-button
          v-for="(item,index) in menuList" :key="index"
          :class="menuIndex===index?'button_view':'button_edit'"
          type="primary"
          @click="onMenuClick(index)"
      >{{ item.title }}</el-button>
    </div>

    <div class="list-content m-t10">
      <div class="xinZu-search-box">
        <span class="xinZu-search-label">关键字</span>
        <el-input
          class="xinZu-search-input"
          v-model="xinZuSearchValue"
          clearable
          placeholder="请输入关键字"
        ></el-input>
        <el-button class="xinZu-search-query-btn button_edit" @click="onSearchBtn"
          >搜索</el-button
        >
        <el-divider
          v-if="menuIndex === 0"
          class="xinZu-search-divider"
          direction="vertical"
        />
        <el-button
          color="#FF7B50"
          style="color: #ffffff"
          class="xinZu-search-view_history-btn"
          @click="toViewHistoryBtn"
          v-if="menuIndex === 0"
        >
          <el-icon><Clock /></el-icon>
          <span class="xinZu-search-view_history-btn-name">查看历史</span>
        </el-button>
      </div>
      <public-table
        :index="false"
        :page="page"
        :tableData="tableData"
        :tableOption="[tableOption, tableOption2, tableOption][menuIndex]"
        @page-change="onPageChange"
      >
        <template #buttons="scope">
          <el-button
            v-if="menuIndex === 0 && scope.row.status === 2"
            @click="toSignContract(scope.row)"
            class="button_edit"
            size="small"
          >
            确认签约</el-button
          >
          <el-button
            v-if="scope.row.status!==-3"
            @click="toHuiShenForm(scope.row)"
            size="small"
            class="button_view"
          >
            查看会审单</el-button
          >
          <el-button v-if="scope.row.status === 1" @click="onDownloadFile(scope.row)" class="button_funtion" size="small">下载合同</el-button>
          <el-tooltip
            v-if="scope.row.status === 3"
            :content="scope.row.flowContent"
            placement="top"
            effect="light"
          >
            <el-button color="#ee2727" size="small" style="color: #ffffff">审批意见</el-button>
          </el-tooltip>
          <el-button v-if="scope.row.status===-3" @click="onEdit(scope.row)" size="small" class="button_edit">编辑</el-button>
        </template>
      </public-table>
    </div>
  </div>

  <!-- 下载弹窗组件 -->
  <download-contract-dialog :tableData="fileData" v-model:visible="visible"/>

  <upload-contract-popup
          ref="uploadContractPopupRef"
          @onSuccess="onSearchBtn"/>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";
import { onMounted, reactive, ref } from "vue";
import PublicTable from "@/components/PublicTable";
import { ElDivider } from "element-plus";
import { Clock } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import DownloadContractDialog from "@/components/downloadContractDialog";
import UploadContractPopup from "./components/uploadContractPopup.vue";

import {
  collaborativeApproval,
  contractApi,
} from "@/api/coordination";

const contractTemplate = ref([]);

const cardList = ref([
  {
    icon: require("@/assets/iconImg/add_icon.png"),
    title: "创建新租表单",
    tip: "请选择新租合同模板",
    path: "/asset/collaborativeApproval/createXinZhuForm/index",
  },
  {
    icon: require("@/assets/iconImg/add_icon.png"),
    title: "创建退租表单",
    tip: "请选择退租合同模板",
    path: "/asset/collaborativeApproval/createThrowLease",
  },
  {
    icon: require("@/assets/iconImg/kaipiao_icon.png"),
    title: "物业验收审批",
    tip: "请选择开票合同模板",
    path: "/asset/collaborativeApproval/propertyAcceptance",
  },
  {
      icon: require("@/assets/iconImg/add_icon.png"),
      title: "上传合同",
      tip: "",
      path: "",
  },
]);

const menuIndex = ref(0);
const menuList = ref([
  {
    title: "新租",
    params: "",
  },
  {
    title: "退租",
    params: "",
  },
  {
    title: "补充协议",
    params: "",
  },
]);

const height = ref(0);

// 查询所有合同模板
const getContractTemplates = (param) => {
  contractApi.getContractTemplates(param).then((res) => {
    res.data.forEach((item) => {
      item.icon = require("@/assets/iconImg/contractTemplate.png");
    });
    contractTemplate.value = res.data;
    isOpen.value = true;
    setTimeout(() => {
      height.value =
        document.querySelectorAll(".template-item")[0].scrollHeight + 15;
    }, 500);
  });
};

const isOpen = ref(false);

const xinZuSearchValue = ref("");
const tableData = ref([]);
const page = reactive({
  total: 0,
  current: 1,
  size: 10,
});

const tableOption = ref([
  { label: "项目名称", prop: "projectName" },
  { label: "合同名称 ", prop: "contractName" },
  { label: "资源名称  ", prop: "assetsName" },
  { label: "资源街道 ", prop: "streetName" },
  {
    label: "承租方 ",
    prop: "leaseCustomers",
    formatter: (val) => {
      if (val && val.length !== 0) {
        return val
          .map((item) => {
            return item.customer_name;
          })
          .join(",");
      }
      return "-";
    },
  },
  { label: "合同金额 ", prop: "contractTotalPrice" },
  {
    label: "月租金(元) ",
    prop: "signMonthlyRent",
    width: 120,
  },
  { label: "经办人", prop: "manageUserName" },
  { label: "状态", prop: "statusValue" },
  {
    label: "操作",
    slot: true,
    width: 500,
    overHidden: false,
    slotName: "buttons",
  },
]);
const tableOption2 = ref([
  { label: "项目名称", prop: "projectName" },
  { label: "合同名称 ", prop: "contractName" },
  { label: "资源名称  ", prop: "assetsName" },
  { label: "资源街道 ", prop: "streetName" },
  { label: "合同金额 ", prop: "contractTotalPrice" },
  {
    label: "租赁周期 ",
    prop: "",
    formatter: (val, row) => {
      if(!row.signStartTime){
          return '-';
      }
      return row.signStartTime + "-" + row.signEndTime;
    },
  },
  { label: "中止月份 ", prop: "rentBreakTime" },
  { label: "经办人", prop: "manageUserName" },
  { label: "状态", prop: "statusValue" },
  {
    label: "操作",
    slot: true,
    width: 500,
    overHidden: false,
    slotName: "buttons",
  },
]);

const onOpenChange = () => {
  isOpen.value = !isOpen.value;
};

const router = useRouter();
const uploadContractPopupRef = ref(null);

// 跳转 "创建新租表单","创建退租表单","物业验收审批" 页面
const toCreateFormPage = (item, index) => {
    if(index===3){
      return uploadContractPopupRef.value.openPopup();
    }
    router.push({ path: item.path });
};

// 查看历史
const toViewHistoryBtn = () => {
  router.push({ path: `/asset/collaborativeApproval/viewHistory` });
};

// 跳转合同模版页
const onTemplateClick = (item) => {
  router.push({ path: `/asset/collaborativeApproval/contract/templateManage` });
};

// 跳转确认签约
const toSignContract = (item) => {
  let customer_name = item.leaseCustomers
    .map((item) => {
      return item.customer_name;
    })
    .join(",");
  router.push({
    path: `/asset/collaborativeApproval/signContract/${item.contractId}/${item.contractName}/${customer_name}`,
  });
};


const fileData = ref([]);
const visible = ref(false);
// 下载合同
const onDownloadFile = (row) => {
  visible.value = true;
  fileData.value = row.files;
}

// 跳转会审单页面
const toHuiShenForm = (item) => {
  let path = "";
  switch (menuIndex.value) {
    case 0:
      path = `/asset/collaborativeApproval/huiShenForm/${item.contractId}`;
      break;
    case 1:
      path = `/asset/collaborativeApproval/huiShenForm/tuizu/${item.rentOutId}`;
      break;
    case 2:
      path = `/asset/collaborativeApproval/huiShenForm/${item.contractId}`;
      break;
  }
  router.push({ path: path });
};

/**
 * 编辑
 * @param row
 */
const onEdit = (row) => {
  if(menuIndex.value === 0){
      router.push({ path: `/asset/collaborativeManagement/createXinZhuForm2/createForm/${row.contractId}`})
  }
  if(menuIndex.value === 1){
      router.push({ path: `/asset/collaborativeManagement/createThrowLease2/throwSteps/${row.rentOutId}`})
  }
}

// 切换 新租/退租/补充协议 按钮事件
const onMenuClick = (index) => {
  xinZuSearchValue.value = "";
  menuIndex.value = index;
  let param = {
    pageNum: 1,
    pageSize: 10,
  };
  switch (index) {
    case 0:
      getNewLeaseFlows(param);
      break;
    case 1:
      getRentOutContractPage(param);
      break;
    case 2:
      getSupplementaryAgreementContract(param);
      break;
  }
};

// 查询新租合同列表
const getNewLeaseFlows = (param) => {
  collaborativeApproval.getNewLeaseFlows(param).then((res) => {
    tableData.value = res.data.content;
    page.total = res.data.totalSize;
  });
};

// 查询退租合同
const getRentOutContractPage = (param) => {
  collaborativeApproval.getRentOutContractPage(param).then((res) => {
    tableData.value = res.data.content;
    page.total = res.data.totalSize;
  });
};

// 查询补充协议合同列表
const getSupplementaryAgreementContract = (param) => {
  collaborativeApproval.getSupplementaryAgreementContract(param).then((res) => {
    tableData.value = res.data.content;
    page.total = res.data.totalSize;
  });
};

// 点击搜索按钮时
const onSearchBtn = () => {
  page.current = 1;
  page.size = 10;
  let param = {
    param: {
      queryName: xinZuSearchValue.value || "",
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  switch (menuIndex.value) {
    case 0:
      getNewLeaseFlows(param);
      break;
    case 1:
      getRentOutContractPage(param);
      break;
    case 2:
      getSupplementaryAgreementContract(param);
      break;
  }
};

// 页码改变时
const onPageChange = (e) => {
  page.current = e.page;
  page.size = e.limit;
  let param = {
    param: {
      queryName: xinZuSearchValue.value || "",
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  switch (menuIndex.value) {
    case 0:
      getNewLeaseFlows(param);
      break;
    case 1:
      getRentOutContractPage(param);
      break;
    case 2:
      getSupplementaryAgreementContract(param);
      break;
  }
};

onMounted(() => {
  getContractTemplates({});
  getNewLeaseFlows({
    pageNum: 1,
    pageSize: 10,
  });
});
</script>

<style scoped>
/* /deep/.el-radio {
  width: 40% !important;
  margin-bottom: 10px;
} */
</style>

<style lang="scss" scoped>
.collaborativeApprovalPage {
  .rightCnBox {
    display: flex;
    align-items: center;
    cursor: pointer;
    .rightCnBox-icon {
      width: 14px;
      height: 14px;
      margin-left: 15px;
    }
    .rightCnBox-title {
      font-size: 12px;
      font-family: SourceHanSansCN-Normal, SourceHanSansCN;
      font-weight: 400;
      color: #ff7b50;
      padding-bottom: 3px;
      border-bottom: 1px solid #ff7b50;
      margin-left: 5px;
    }
  }

  .template-list {
    display: flex;
    flex-wrap: wrap;
    .template-item {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-right: 62px;
      margin-bottom: 15px;
      padding-left: 40px;

      .template-icon {
        width: 22px;
        height: 22px;
      }
      .template-title {
        font-size: 14px;
        font-family: SourceHanSansCN-Normal, SourceHanSansCN;
        font-weight: 400;
        color: #ff7b50;
        margin-left: 8px;
        padding-bottom: 5px;
        border-bottom: 2px solid #ff7b50;
      }
    }
  }

  .form-list {
    display: flex;
    flex-wrap: wrap;

    .card-box {
      width: 232px;
      height: 82px;
      background: #ffffff;
      box-shadow: 0px 4px 14px 0px rgba(0, 0, 0, 0.05);
      border-radius: 20px;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      margin-right: 28px;

      .card-icon {
        width: 22px;
        height: 22px;
      }
      .card-title {
        margin-left: 8px;
        font-size: 14px;
        font-family: SourceHanSansCN-Normal, SourceHanSansCN;
        font-weight: 400;
        color: #ff7b50;
      }
    }
  }

  .menu-list {
    display: flex;

    .menu-item.active {
      background: #ff7b50;
      border: none !important;
      span {
        color: #ffffff;
        font-weight: 500;
      }
    }
    .menu-item {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px 10px;
      border-radius: 6px;
      border: 1px solid #666666;
      margin-right: 68px;
      cursor: pointer;

      span {
        font-size: 14px;
        font-family: SourceHanSansCN-Normal, SourceHanSansCN;
        font-weight: 400;
        color: #666666;
      }
    }
  }

  .list-content {
    .xinZu-search-box {
      margin-top: 30px;
      .xinZu-search-label {
        font-size: 14px;
        font-family: SourceHanSansCN-Medium, SourceHanSansCN;
        font-weight: 500;
        color: #1a1a1a;
      }
      // :deep(.xinZu-search-input .el-input__wrapper)  {
      //   background-color:  #F7F7F7 !important;
      // }
      .xinZu-search-input {
        width: 344px;
        margin-left: 8px;
        margin-right: 17px;
      }
      .xinZu-search-divider {
        margin: 0 15px;
        height: 3em !important;
      }
      // .xinZu-search-query-btn {
      // }
      .xinZu-search-view_history-btn {
        &-name {
          margin-left: 6px;
        }
      }
    }
  }
}
</style>
